//
//  CedarDataBaseStore.m
//  CedarSuperCloud
//
//  Created by menchao on 2017/11/24.
//  Copyright © 2017年 cedarhd. All rights reserved.
//

#import "CedarDataBaseStore.h"
#import "YTKKeyValueStore.h"
#import <MJExtension.h>
#import "YYCache.h"
#import "AppCongifure.h"
#import "DatabaseStoreHelper.h"

static NSString *const DataBaseName = @"CedarDataBase";

//应用配置
#define APP_CONFIGUE_DATABASE_NAME  @"CedarAppConfigueDB"

#define APP_TOKEN  @"apptoken"
#define APP_LOGIN_INFO  @"applogininfo"
#define  APP_HOME_GUIDE  @"AppHomeGuide"
#define  APP_UPDATE_TIME_KEY  @"AppUpdateTimeKey"//app 更新

#define  Using_New_Cache

@interface CedarDataBaseStore()

@property (nonatomic, strong) YTKKeyValueStore *store;
@property (nonatomic, copy) NSString *databaseName;
@property (nonatomic, copy) NSString *tableName;
@property (nonatomic,copy) NSString *loginToken;
@property (nonatomic,strong) LoginInfoRsp *tempLoginInfo;
@property (nonatomic,strong) DeviceInfoModel *tempDeviceInfo;//缓存设备信息，为了更新push token

@end

@implementation CedarDataBaseStore

+ (instancetype)shareInstance{
    static CedarDataBaseStore *dbs = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        dbs = [[CedarDataBaseStore alloc] init];
        dbs.loginToken = nil;
        dbs.tempLoginInfo = nil;
        dbs.tempDeviceInfo = nil;
    });
    return dbs;
}

- (void)syncUserData{
#ifdef Using_New_Cache
    #if DEBUG
    CLog(@"appLoginToken: %@,appVersion:%@,appUpdateTime:%@",[AppCongifure shareInstance].appLoginToken,[AppCongifure shareInstance].appVersion, [AppCongifure shareInstance].appUpdateTime);
    LoginInfoRsp *login = [self getLoginInfo];
    CLog(@"userName: %@,idCardNo: %@,hasBindCard:%ld",login.userName,login.idCardNo,(long)login.hasBindCard);
    #endif
    if( [[AppCongifure shareInstance] isSyncUserData]){
      CLog(@"user data  has sync");
      return;
    }
    //把老版本的数据同步到新的配置
    YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
    //token
    BOOL isContainKey = [diskCache containsObjectForKey:APP_TOKEN];
    if(isContainKey){
        NSString *loginToken = (NSString *)[diskCache objectForKey:APP_TOKEN];
        // self.loginToken = (NSString *)[diskCache objectForKey:APP_TOKEN]
        [[AppCongifure shareInstance] saveAppLoginToken:loginToken];
    }
    
    //向导
    isContainKey = [diskCache containsObjectForKey:APP_HOME_GUIDE];
    if(isContainKey){
        NSString *appVersion = (NSString *)[diskCache objectForKey:APP_HOME_GUIDE];
         [[AppCongifure shareInstance] saveAppVersion:appVersion];
    }
    
    //时间
    isContainKey = [diskCache containsObjectForKey:APP_UPDATE_TIME_KEY];
    if (isContainKey) {
        NSString *appUpdateTime = (NSString *)[diskCache objectForKey:APP_UPDATE_TIME_KEY];
        [[AppCongifure shareInstance] saveAppUpdateTime:appUpdateTime];
    }
    
    //用户信息
    isContainKey = [diskCache containsObjectForKey:APP_LOGIN_INFO];
    if(isContainKey){
        NSString *info = (NSString *)[diskCache objectForKey:APP_LOGIN_INFO];
        LoginInfoRsp *loginInfo = [LoginInfoRsp mj_objectWithKeyValues:info];
        [[DatabaseStoreHelper shareInstance]saveObject:loginInfo className:@"LoginInfoRsp"];
    }
    CLog(@"user data sync ok");
    [[AppCongifure shareInstance] saveIsSyncUserData:YES];
#else
    
#endif
}


- (void)setTokenForAppConfige:(NSString *)token{
#ifdef Using_New_Cache
    [[AppCongifure shareInstance] saveAppLoginToken:token];
    self.loginToken = nil;
#else
    if (!IsEmptyStr(token)) {
        YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
        [diskCache setObject:token forKey:APP_TOKEN];
    }else{//移除
        YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
        [diskCache removeObjectForKey:APP_TOKEN];
    }
    self.loginToken = nil;
#endif
}

- (NSString *)getTokenForAppConfige{
    #ifdef Using_New_Cache
    if (!self.loginToken) {
        self.loginToken = [[AppCongifure shareInstance] appLoginToken];
    }
    return self.loginToken;
#else
    if (IsEmptyStr(self.loginToken)) {
        YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
        BOOL isContainKey = [diskCache containsObjectForKey:APP_TOKEN];
        if(isContainKey){
            self.loginToken = (NSString *)[diskCache objectForKey:APP_TOKEN];
        }
        if (IsEmptyStr(self.loginToken)) {
            self.loginToken = nil;
            CLog(@"loginToken is nil");
        }
    }
    return self.loginToken;
#endif
}

- (void)saveLoginInfo:(LoginInfoRsp *)loginInfo{
#ifdef Using_New_Cache
    if (loginInfo) {
        [[DatabaseStoreHelper shareInstance]saveObject:loginInfo className:@"LoginInfoRsp"];
    }else{
        [[DatabaseStoreHelper shareInstance]deleteObjectByClassName:@"LoginInfoRsp"];
    }
    self.tempLoginInfo = nil;
#else
    if (loginInfo) {
        NSDictionary *dict = [loginInfo mj_keyValues];
        if(dict){
            NSString *str = [CedarTools dictToJsonStr:dict];
            YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
            [diskCache setObject:str forKey:APP_LOGIN_INFO];
        }
    }else{
        YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
        [diskCache removeObjectForKey:APP_LOGIN_INFO];
    }
    self.tempLoginInfo = nil;
#endif
}

- (LoginInfoRsp *)getLoginInfo{
#ifdef Using_New_Cache
    if (!self.tempLoginInfo) {
        self.tempLoginInfo = [[DatabaseStoreHelper shareInstance] getObjectWithClassName:@"LoginInfoRsp"];
    }
    return self.tempLoginInfo;
#else
    if (!self.tempLoginInfo) {
        YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
        BOOL isContainKey = [diskCache containsObjectForKey:APP_LOGIN_INFO];
        if(isContainKey){
            NSString *info = (NSString *)[diskCache objectForKey:APP_LOGIN_INFO];
            self.tempLoginInfo = [LoginInfoRsp mj_objectWithKeyValues:info];
        }
    }
    return self.tempLoginInfo;
#endif
}


- (void)setAppGuideConfige:(BOOL)hasShow{
#ifdef Using_New_Cache
    if (hasShow) {
        NSString *appVersion = [PlatformTools appVersion];
        [[AppCongifure shareInstance] saveAppVersion:appVersion];
    }else{
         [[AppCongifure shareInstance] saveAppVersion:nil];
    }
#else
    if (hasShow) {
        YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
        NSString *appVersion = [PlatformTools appVersion];
        if(appVersion){
             [diskCache setObject:appVersion forKey:APP_HOME_GUIDE];
        }
    }else{
        YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
        [diskCache removeObjectForKey:APP_HOME_GUIDE];
    }
#endif
   
}

- (BOOL)getAppGuideConfigeIfShow{
#ifdef Using_New_Cache
    NSString *cacheVersion = [[AppCongifure shareInstance] appVersion];
    NSString *appVersion = [PlatformTools appVersion];
    BOOL isShow = NO;
    if (![appVersion isEqualToString:cacheVersion]) {//当前版本和缓存版本是否一样
        isShow = YES;
    }
    return isShow;
#else
    YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
    BOOL isContainKey = [diskCache containsObjectForKey:APP_HOME_GUIDE];
    BOOL isShow = NO;
    if(isContainKey){
        NSString *cacheVersion = (NSString *)[diskCache objectForKey:APP_HOME_GUIDE];
        NSString *appVersion = [PlatformTools appVersion];
        CLog(@"cacheVersion: %@,appVersion: %@",cacheVersion,appVersion);
        if (![appVersion isEqualToString:cacheVersion]) {//当前版本和缓存版本是否一样
            isShow = YES;
        }
    }else{
        isShow = YES;
    }
    return isShow;
#endif
}

#pragma mark app update time

- (void)setAppUpdateTime{
#ifdef Using_New_Cache
    NSString *time = [PlatformTools getCurrentTime];
    [[AppCongifure shareInstance] saveAppUpdateTime:time];
#else
    YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
    NSString *time = [PlatformTools getCurrentTime];
#if DEBUG
    CLog(@"curretn time: %@",time);
#endif
    if(time){
        [diskCache setObject:time forKey:APP_UPDATE_TIME_KEY];
    }
#endif
}

- (BOOL)isNeedCheckUpdateApp{
#ifdef Using_New_Cache
    CGFloat hours = 2; //设置2小时
    NSString *startTime = [AppCongifure shareInstance].appUpdateTime;
    NSString *nowTime = [PlatformTools getCurrentTime];
    NSTimeInterval diffTime =  [PlatformTools dateTimeDifferenceWithStartTime:startTime endTime:nowTime];
    if(diffTime>=hours*60*60){//超过清除缓存
        CLog(@"time expire need clear cache %f",diffTime);
        //[diskCache removeObjectForKey:APP_UPDATE_TIME_KEY];
        if(nowTime){
            [[AppCongifure shareInstance] saveAppUpdateTime:nowTime];
         }
        return YES;
    }else if(diffTime<0){
        if(nowTime){
            [[AppCongifure shareInstance] saveAppUpdateTime:nowTime];
          }
        return YES;
    }
    return NO;
#else
    CGFloat hours = 2; //设置2小时
    YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CONFIGUE_DATABASE_NAME];
    BOOL isContainKey = [diskCache containsObjectForKey:APP_UPDATE_TIME_KEY];
    if(isContainKey){
        NSString *startTime = (NSString *)[diskCache objectForKey:APP_UPDATE_TIME_KEY];
        NSString *nowTime = [PlatformTools getCurrentTime];
        NSTimeInterval diffTime =  [PlatformTools dateTimeDifferenceWithStartTime:startTime endTime:nowTime];
#if DEBUG
        CLog(@"startTime: %@ ,nowTime :%@ ,diffTime: %.1f min",startTime,nowTime,diffTime/60);
#endif
         if(diffTime>=hours*60*60){//超过清除缓存
            CLog(@"time expire need clear cache %f",diffTime);
            //[diskCache removeObjectForKey:APP_UPDATE_TIME_KEY];
            if(nowTime){
                [diskCache setObject:nowTime forKey:APP_UPDATE_TIME_KEY];
            }
            return YES;
        }else if(diffTime<0){
            if(nowTime){
                [diskCache setObject:nowTime forKey:APP_UPDATE_TIME_KEY];
            }
            return YES;
        }
        return NO;
    }else{
        NSString *time = [PlatformTools getCurrentTime];
        if(time){
            [diskCache setObject:time forKey:APP_UPDATE_TIME_KEY];
        }
        return NO;
    }
#endif
}


#pragma mark - push token

- (void)saveDeviceInfo:(DeviceInfoModel *)deviceInfo{
    if (deviceInfo) {
        [[DatabaseStoreHelper shareInstance]saveObject:deviceInfo className:@"DeviceInfoModel"];
    }else{
        [[DatabaseStoreHelper shareInstance]deleteObjectByClassName:@"DeviceInfoModel"];
    }
    self.tempDeviceInfo = nil;
}

- (DeviceInfoModel *)getDeviceInfo{
    if (!self.tempDeviceInfo) {
        self.tempDeviceInfo = [[DatabaseStoreHelper shareInstance] getObjectWithClassName:@"DeviceInfoModel"];
    }
    return self.tempDeviceInfo;
}

@end
